package com.jandar.spider.utils;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import org.springframework.stereotype.Component;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import java.util.concurrent.TimeUnit;

/**
 * @author gaochenyang
 * @title: OkHttpUtils
 * @projectName java_reptile
 * @description: TODO
 * @date 2020/6/210:42 下午
 */

@Component
@Slf4j
public class OkHttpUtils {

    private final static int READ_TIMEOUT = 30;
    private final static int CONNECT_TIMEOUT = 30;
    private final static int WRITE_TIMEOUT = 30;

    public OkHttpClient okHttpCline() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.retryOnConnectionFailure(true);
        builder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
        builder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
        builder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder.build();
    }

    /**
     * get使用代理的请求
     *
     * @param url
     * @return
     */
    public String okhttpGet(String url) {
        log.info("当前请求的URL：{}", url);
        Response response;
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        try {
            Call call = okHttpCline().newCall(request);
            response = call.execute();
            String html = response.body().string();
            return html;
        } catch (Exception e) {
            log.error("请求失败：{}.", e.toString());
            e.printStackTrace();
            return "";
        }
    }
    public JSONObject okhttpPost(String url, JSONObject param) {
        JSONObject res = new JSONObject();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param.toJSONString());
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            Thread.sleep(1000L);
            Response response = okHttpCline().newCall(request).execute();
            res = JSONObject.parseObject(response.body().string());
            response.close();
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
        return res;
    }

    /**
     * 通用POST请求
     *
     * @param url
     * @return
     */
    public String hostPostHTML(String url, RequestBody requestBody, String cookie) {
        Response response = null;
        try {
            Request request = new Request.Builder()
                    .header("Cookie", cookie)
                    .post(requestBody)
                    .url(url)
                    .build();
            Call call = okHttpCline().newCall(request);
            response = call.execute();
            return response.body() != null ? response.body().string() : "";
        } catch (Exception e) {
            if (response != null) {
                response.close();
            }
            log.error("页面请求报错: " + e.toString());
            return "";
        }
    }
}
